import { API_CONFIG } from '../api-config';

// API基础URL配置
const API_BASE_URL = API_CONFIG.BASE_URL;

// 通用请求头
const defaultHeaders = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
};

// 通用请求方法
async function request(endpoint, options = {}) {
  const url = `${API_BASE_URL}${endpoint}`;
  const fetchOptions = {
    method: options.method || 'GET',
    headers: { 
      ...defaultHeaders,
      ...options.headers 
    },
    mode: 'cors',
    credentials: 'omit',
    ...options
  };
  
  if (options.body && typeof options.body === 'object') {
    fetchOptions.body = JSON.stringify(options.body);
  }

  try {
    console.log(`API请求: ${options.method || 'GET'} ${url}`);
    if (options.body) {
      console.log('请求数据:', JSON.stringify(options.body, null, 2));
    }
    
    const response = await fetch(url, fetchOptions);
    console.log(`API响应状态: ${response.status} ${response.statusText}`);
    
    // 处理特定错误情况
    if (response.status === 502 || response.status === 504) {
      console.error(`网关错误 (${response.status}): 无法连接到后端服务`);
      throw new Error(`网关错误 (${response.status}): 无法连接到后端服务，请检查服务器状态`);
    }
    
    // 尝试获取响应JSON，包括错误响应
    let result;
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      result = await response.json();
      console.log('API响应数据:', result);
    } else {
      result = await response.text();
      console.log('API响应文本:', result.substring(0, 500) + (result.length > 500 ? '...' : ''));
    }
    
    if (!response.ok) {
      // 对于JSON错误响应，提取错误信息
      const errorMessage = typeof result === 'object' && result.error 
        ? result.error 
        : `HTTP错误! 状态码: ${response.status}`;
        
      console.error('API错误响应:', errorMessage);
      throw new Error(errorMessage);
    }
    
    return result;
  } catch (error) {
    console.error('API请求错误:', error.message);
    console.error('错误详情:', error);
    
    // 网络错误特殊处理
    if (error.message === 'Failed to fetch') {
      error.message = '网络请求失败，请检查网络连接或服务器状态';
    }
    
    throw error;
  }
}

// 导出具体API方法
export const api = {
  // 统计相关API
  statistics: {
    getAll: () => request('/statistics'),
  },
  
  // 策略表相关API
  betStrategyTables: {
    getAll: () => request('/bet-strategy-tables'),
    create: (data) => request('/bet-strategy-tables', { method: 'POST', body: data }),
    update: (id, data) => request(`/bet-strategy-tables/${id}`, { method: 'PUT', body: data }),
    delete: (id) => request(`/bet-strategy-tables/${id}`, { method: 'DELETE' }),
    setDefault: (id) => request(`/bet-strategy-tables/${id}/set-default`, { method: 'POST' }),
  },
  
  // 游戏相关API
  game: {
    getCardsStatus: () => request('/cards-status'),
    getHistory: () => request('/history'),
    resetGame: () => request('/reset-game', { method: 'POST' }),
    deal: (data) => request('/deal', { method: 'POST', body: data }),
    clearHistory: () => request('/clear-history', { method: 'POST' }),
    dealOnly: () => request('/deal', { method: 'POST' }),
    clear: () => request('/clear', { method: 'POST' }),
    getState: () => request('/state'),
    placeBet: (data) => request('/bet', { method: 'POST', body: data }),
  },
  
  // 模拟相关API
  simulations: {
    getAll: () => request('/simulations'),
    run: (data) => request('/simulations/run', { method: 'POST', body: data }),
    getById: (id) => request(`/simulation/${id}`),
    clearAll: () => request('/clear-simulations', { method: 'POST' }),
    clearById: (id) => request(`/clear-simulation/${id}`, { method: 'POST' }),
  }
};

export default api; 